export default function useBt() {

    const serviceUUID = '0000F040-0000-1000-8000-00805F9B34FB'; // 主服务UUID
    const writeUUID = '0000F041-0000-1000-8000-00805F9B34FB'; // 写属性UUID
    const readUUID = '0000F042-0000-1000-8000-00805F9B34FB'; // 读属性UUID

    // 蓝牙已初始化
    const adapterOpend = ref(false)
    // 搜索状态
    const startSearch = ref(false)

    const findTimer = ref(null)

    // 蓝牙连接状态
    const connectStatus = ref(false)

    // 设备列表
    const deviceList = ref([])

    // 设备Id
    const deviceId = ref('')

    // * 主服务 UUID 0000F040-0000-1000-8000-00805F9B34FB
    // * 写属性 UUID 0000F041-0000-1000-8000-00805F9B34FB 
    // * 读属性(非通知)UUID 0000F042-0000-1000-8000-00805F9B34FB

    /**
     * 统一安卓与IOS端deviceId展示
     * @param advertisData 
     * 在安卓设备中，获取到的 deviceId 为设备 MAC 地址，iOS 上则为设备 uuid，
     * 因此为了展示一致需要将ios的展示进行输入（当然IOS的连接还是得用获取到的uuid）
     */
    function uuid2Mac(advertisData) {
        if (advertisData) {
            let mac = Array.prototype.map
                .call(new Uint8Array(bf), (x) => ("00" + x.toString(16)).slice(-2))
                .join(":");
            mac = mac.toUpperCase();
            return mac;
        }
    }

    // 初始化蓝牙
    async function initBluetooth() {
        try {
            stopBluetoothDevicesDiscovery(); // 停止扫描
        } catch (e) {
            //TODO handle the exception
        }
        return new Promise((resolve, reject) => {
            if (adapterOpend.value) {
                console.log("蓝牙适配器已打开")
                resolve(true)
                return
            }
            wx.openBluetoothAdapter({
                success(res) {
                    adapterOpend.value = true
                    console.log("=====*****蓝牙适配器已打开")
                    resolve(true)
                },
                fail(error) { //用来判断蓝牙是否已打开
                    if (error.errMsg.includes('already opened')) {
                        adapterOpend.value = true
                        console.log("=====*****蓝牙适配器已打开")
                        resolve(true)
                        return;
                    }
                    reject(error)
                    adapterOpend.value = false
                    console.log("=====*****蓝牙适初始化失败", error)
                }
            })
        })
    }

    /**
     * 开始搜寻蓝牙
     * @param options 
     * @param {array} options.services  要搜索的蓝牙设备主服务的 UUID 列表
     */
    async function startBluetoothDevicesDiscovery(options) {
        return new Promise((resolve, reject) => {
            if (startSearch.value) {
                console.log("已开启蓝牙扫描，勿重复开启")
                resolve(true)
                return
            }
            startSearch.value = true
            wx.startBluetoothDevicesDiscovery({
                allowDuplicatesKey: true,
                // services: options.services,
                success(res) {
                    console.log('搜索成功', res);
                    resolve(true)
                },
                fail(error) {
                    reject(error)
                    startSearch.value = false
                },
            })
        })
    }

    /**
     * 监听搜索到的设备
     * @param options 
     * options.keywords  蓝牙名称筛选关键字
     */
    async function onBluetoothDeviceFound(options) {
        return new Promise((resolve, reject) => {
            let {
                keywords
            } = options
            // 超时自动结束
            findTimer.value = setTimeout(() => {
                clearTimeout(findTimer.value)
                if (!connectStatus.value) {
                    stopBluetoothDevicesDiscovery(); // 停止扫描
                    reject({
                        success: false
                    })
                    console.log('蓝牙扫描超时，自动关闭任务')
                }
            }, 3000); //时间根据自己的需求定
            wx.onBluetoothDeviceFound(res => {
                let devices = res.devices;
                for (let i = 0; i < devices.length; i++) {
                    let device = devices[i];
                    if (!device.name && !device.localName) {
                        return
                    }
                    console.log('device', device)
                    // 获取设备MAC地址，并根据关键字过滤
                    // let systemInfo = wx.getSystemInfoSync()
                    // let iosDevice = systemInfo.system.toLowerCase().indexOf("ios") > -1;
                    // let deviceMac = iosDevice ? uuid2Mac(device.advertisData) : device.deviceId
                    // keywords
                    if (keywords === device.name) {
                        stopBluetoothDevicesDiscovery()
                        resolve({
                            ...device,
                            // deviceMac,
                            success: true
                        })
                        break;
                    }
                }
            })

        })
    }

    function stopBluetoothDevicesDiscovery() {
        startSearch.value = false
        wx.stopBluetoothDevicesDiscovery(); // 停止扫描
    }

    /**
     * 处理蓝牙连接
     * @param {string} options.deviceId 蓝牙设备id，连接用
     */
    async function createBLEConnection(options) {
        return new Promise((resolve, reject) => {
            let {
                deviceId: deviceCode
            } = options;
            deviceId.value = deviceCode
            console.log('---deviceId', deviceId.value)
            // if (connectStatus.value) {
            // 	wx.closeBLEConnection({
            // 		deviceId
            // 	})
            // }
            let timeout = 3000 //根据自己需求去定
            console.log('开始连接蓝牙--', deviceId.value)
            // _this.stopBLEDevicesTask() // todo
            wx.createBLEConnection({
                deviceId: deviceId.value,
                timeout,
                success(res) {
                    if (res.errCode === 0) {
                        console.log('蓝牙连接成功-----', res)
                        connectStatus.value = true
                        resolve(res)
                    } else {
                        console.log('蓝牙连接失败-----', res)
                        connectStatus.value = false
                        reject(res)
                    }
                },
                fail(err) {
                    console.log('蓝牙连接失败-----', err)
                    connectStatus.value = false
                    reject(err)
                }
            })
        })
    }

    /**
     * 连接成功后，要获取蓝牙的所有服务 进而根据项目需求的服务 去获取对应的特征 来进行读写操
     * @param deviceId  蓝牙设备Id，来自createBLEConnection调用
     */
    async function getBLEDeviceServices(deviceId = '') {
        return new Promise((resolve, reject) => {
            wx.getBLEDeviceServices({
                deviceId,
                success(res) {
                    console.log('getBtDeviceServices res：', res)
                    resolve({
                        sucess: true
                    })
                },
                fail: (res) => {
                    reject({
                        sucess: false,
                        data: res.errMsg
                    })
                    console.log("服务获取失败------------->", res.errMsg);
                },
            });
        })
    }


    // 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
    // https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth-ble/wx.getBLEDeviceCharacteristics.html
    async function getBLEDeviceCharacteristics() {
        return new Promise((resolve, reject) => {
            wx.getBLEDeviceCharacteristics({
                deviceId: deviceId.value,
                serviceId: serviceUUID,
                success: (res) => {
                    console.log('Characteristics found:', res.characteristics);
                    resolve()
                },
                fail: (err) => {
                    console.error('Failed to get characteristics:', err);
                    reject(err)
                }
            });
        })
    }

    // 检测是否连接中, 如果未连接则尝试重新连接
    async function checkAndReconnectDevice(deviceId) {
        return new Promise((resolve, reject) => {
            wx.getConnectedBluetoothDevices({
                services: [serviceUUID],
                success: (res) => {
                    const isConnected = res.devices.some(device => device.deviceId === deviceId);
					console.log('getConnectedBluetoothDevices', res)
					console.log('deviceId', `${isConnected} --- ${deviceId}`)
                    if (!isConnected) {
                        resolve(false)
                        console.log('Device not connected, reconnecting...');
                    } else {
                        console.log('Device already connected');
                        resolve(true)
                    }
                },
                fail: (err) => {
                    resolve(false)
                }
            });
        })
    };

    // 读取充电状态
    async function readChargeStatus() {
        return new Promise((resolve, reject) => {
            // 监听特征值变化
            wx.onBLECharacteristicValueChange((res) => {
                console.log('Characteristic value changed:', res);
                const status = new DataView(res.value).getUint8(19);
                if (status === 0x46) {
                    console.log('charging data', res.value);
                    console.log('Charging in progress');
                    resolve({
                        charging: true,
                        hours: new DataView(res.value).getUint8(2),
                        minutes: new DataView(res.value).getUint8(3),
                    })
                } else {
                    console.log('Not charging');
                    resolve({
                        charging: false,
                        hours: 0,
                        minutes: 0,
                    })
                }
            });
            wx.readBLECharacteristicValue({
                deviceId: deviceId.value,
                serviceId: serviceUUID,
                characteristicId: readUUID,
                success: (res) => {
                    console.log('Read characteristic value request sent successfully');
                },
                fail: (err) => {
                    reject({
                        charging: false,
                        hours: 0,
                        minutes: 0,
                        errMsg: `${err.errCode}:${err.errMsg}`
                    })
                    console.error('Failed to read charge status:', err);
                }
            });
        });
    };


    async function sendCargeCommand(hours, minutes) {
        return new Promise((resolve, reject) => {
            const buffer = new ArrayBuffer(20);
            const dataView = new DataView(buffer);
            dataView.setUint8(0, 0xFE); // Header
            dataView.setUint8(1, 0xD5); // Command
            dataView.setUint8(2, hours); // Hours
            dataView.setUint8(3, minutes); // Minutes
            dataView.setUint8(19, 0x45); // Status byte

            console.log('Sending charge command:', dataView);

            wx.writeBLECharacteristicValue({
                deviceId: deviceId.value,
                serviceId: serviceUUID,
                characteristicId: writeUUID,
                value: buffer,
                writeType: 'write',
                success: () => {
                    console.log('Charge command sent successfully');
                    resolve()
                },
                fail: (err) => {
                    console.error('Failed to send charge command:', err);
                    reject(err)
                }
            });
        });
    }

    return {
        initBluetooth,
        startBluetoothDevicesDiscovery,
        onBluetoothDeviceFound,
        createBLEConnection,
        getBLEDeviceServices,
        getBLEDeviceCharacteristics,
        sendCargeCommand,
        readChargeStatus,
        checkAndReconnectDevice,
    }
}